<template>
  <div class="carbon-platform">
    <!-- 保留原页面的导航栏、横幅、页脚等部分 -->
    <!-- Preloader -->
    <div class="preloader-wrapper" v-if="isLoading">
      <div class="preloader"></div>
    </div>

    <nav class="navbar sticky-top bg-white shadow-sm py-3">
      <!-- 导航栏内容保持不变 -->
      <div class="container">
        <div class="d-flex justify-content-between align-items-center w-100">
          <!-- 网站标志 -->
          <div class="navbar-logo">
            <span class="logo-icon">🌱</span>
            <span class="logo-text">绿碳平台</span>
          </div>

          <!-- 中间导航链接 - 桌面版 -->
          <ul class="navbar-nav list-unstyled d-flex flex-row gap-3 gap-lg-5 justify-content-center flex-wrap align-items-center mb-0 fw-bold flex-grow-1 mx-4">
            <li class="nav-item">
              <a href="/index" class="nav-link text-dark hover:text-primary transition-colors">首页</a>
            </li>
            <li class="nav-item">
              <a href="/shop" class="nav-link text-dark hover:text-primary transition-colors">碳积分市场</a>
            </li>
            <li class="nav-item">
              <a href="/blog" class="nav-link text-dark hover:text-primary transition-colors">博客</a>
            </li>
            <li class="nav-item">
              <a href="/contact" class="nav-link text-dark hover:text-primary transition-colors">联系我们</a>
            </li>
            <li class="nav-item">
              <a href="/about" class="nav-link text-dark hover:text-primary transition-colors">关于我们</a>
            </li>
            <li class="nav-item">
              <a href="/order" class="nav-link text-dark hover:text-primary transition-colors">我的订单</a>
            </li>
          </ul>

          <!-- 右侧功能区 - 使用emoji图标 -->
          <div class="d-flex align-items-center gap-4 gap-lg-5">
            <!-- 搜索按钮 -->
            <button class="btn p-2 text-dark hover:text-primary transition-colors" aria-label="搜索">
              <span class="fs-5">🔍</span>
            </button>

            <!-- 购物车 -->
            <a href="/cart" class="btn p-2 text-dark hover:text-primary transition-colors position-relative" aria-label="购物车">
              <span class="fs-5">🛒</span>
              <!--              <span class="position-absolute top-0 right-0 btn-success text-white text-xs rounded-full h-5 w-5 flex items-center justify-center" style="border-radius: 50%;">3</span>-->
            </a>

            <!-- 用户菜单 -->
            <div class="dropdown">
              <button class="btn p-2 text-dark hover:text-primary transition-colors" type="button" data-bs-toggle="dropdown" aria-expanded="false" aria-label="用户菜单">
                <span class="fs-5">👤</span>
              </button>
              <ul class="dropdown-menu dropdown-menu-end">
                <li><a class="dropdown-item" href="/login">登录</a></li>
                <li><a class="dropdown-item" href="/register">注册</a></li>
                <li><a class="dropdown-item" href="/account">我的账户</a></li>
              </ul>
            </div>

            <!-- 移动端菜单按钮 -->
            <button class="btn d-lg-none p-2 text-dark" type="button" data-bs-toggle="offcanvas" data-bs-target="#mobileMenu" aria-label="菜单">
              <span class="fs-5">☰</span>
            </button>
          </div>
        </div>
      </div>
    </nav>

    <!-- 顶部横幅部分 -->
    <div class="banner-section">
      <div class="container">
        <div class="banner-content">
          <h1 class="banner-title text-white">商品详情</h1>
        </div>
      </div>
    </div>

    <!-- 商品详情主内容 -->
    <main class="SingleProduct-page py-5">
      <div class="container">
        <!-- 商品主体区域 -->
        <div class="row g-0">
          <!-- 左侧商品图片 -->
          <div class="col-lg-7">
            <div class="row g-3">
              <!-- 小图列表 -->
              <div class="col-2">
                <div class="thumbnail-list">
                  <div class="thumbnail-item"
                       v-for="(img, index) in product.images"
                       :key="index"
                       :class="{active: activeImageIndex === index}"
                       @click="activeImageIndex = index">
                    <img :src="img" :alt="product.name" class="img-fluid">
                  </div>
                </div>
              </div>

              <!-- 主图展示 -->
              <div class="col-9">
                <div class="product-main-image">
                  <img :src="product.images[activeImageIndex]"
                       :alt="product.name"
                       class="img-fluid">
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧商品信息 -->
          <div class="col-4">
            <div class="product-details">
              <h1 class="product-title">{{ product.name }}</h1>

              <!-- 评分 -->
              <div class="product-rating mb-3">
                <span class="stars">
                  <span v-for="n in 5" :key="n">
                    <span v-if="n <= product.rating">★</span>
                    <span v-else>☆</span>
                  </span>
                </span>
                <span class="reviews">({{ product.reviews }}条评价)</span>
              </div>

              <!-- 价格 -->
              <div class="product-price mb-4">
                <span class="current-price">¥{{ product.pricePerCredit }}/积分</span>
                <span class="original-price">减排量: {{ product.carbonReduction }}吨CO₂</span>
              </div>

              <!-- 项目简介 -->
              <div class="product-description mb-4">
                <p>{{ product.shortDescription }}</p>
              </div>

              <!-- 项目标签 -->
              <div class="project-tags mb-4">
                <span class="badge bg-primary me-2" v-for="tag in product.tags" :key="tag">{{ tag }}</span>
              </div>

              <!-- 数量选择 -->
              <div class="quantity-selector mb-4">
                <label class="form-label">购买积分数量：</label>
                <div class="input-group" style="width: 150px;">
                  <button class="btn btn-outline-secondary"
                          type="button"
                          @click="quantity > 1 ? quantity-- : ''">-
                  </button>
                  <input type="number"
                         v-model.number="quantity"
                         min="1"
                         :max="product.availableQuantity"
                         class="form-control text-center">
                  <button class="btn btn-outline-secondary"
                          type="button"
                          @click="quantity < product.availableQuantity ? quantity++ : ''">+
                  </button>
                </div>
                <div class="stock-status mt-2">
                  <span class="text-success">
                    可购买: {{ product.availableQuantity }} 积分
                  </span>
                </div>
              </div>

              <!-- 操作按钮 -->
              <div class="product-actions mb-5">
                <button class="btn btn-primary btn-lg me-3" @click="addToCart">
                  加入购物车
                </button>
                <button class="btn btn-outline-primary btn-lg" @click="buyNow">
                  立即购买
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 页脚部分保持不变 -->
    <footer class="main-footer">
      <div class="container">
        <div class="footer-bottom">
          <p class="copyright">© 2025 绿碳平台 版权所有 | 京ICP备12345678号</p>
        </div>
      </div>
    </footer>
  </div>
</template>

<script>
export default {
  name: 'CarbonProjectDetail',
  data() {
    return {
      isLoading: false,
      cartItems: [],
      activeImageIndex: 0,
      quantity: 1,
      product: {},
      newReview: {
        rating: 0,
        content: '',
        name: '',
        email: ''
      },
      relatedProducts: [],
      categories: [
        {id: 1, name: '全部项目'},
        {id: 2, name: '森林碳汇'},
        {id: 3, name: '光伏减排'},
        {id: 4, name: '风电项目'},
        {id: 5, name: '甲烷回收'},
        {id: 6, name: '节能项目'},
        {id: 7, name: '氢能项目'},
        {id: 8, name: '碳捕获'}
      ]
    }
  },
  computed: {
    cartSubtotal() {
      return this.cartItems.reduce((total, item) => {
        return total + (item.price * item.quantity)
      }, 0).toFixed(2)
    },
    cartTotal() {
      const subtotal = parseFloat(this.cartSubtotal)
      const fee = subtotal >= 999 ? 0 : 50
      return (subtotal + fee).toFixed(2)
    }
  },
  created() {
    // 从路由参数获取项目ID
    const productId = this.$route.params.id
    this.fetchProjectDetails(productId)
    this.fetchRelatedProjects()
  },
  methods: {
    getCategoryName(categoryId) {
      const category = this.categories.find(cat => cat.id === categoryId)
      return category ? category.name : '未知分类'
    },
    fetchProjectDetails(id) {
      // 实际项目中应替换为API请求
      this.isLoading = true

      // 模拟项目数据，实际应从API获取
      const mockProjects = [
        {
          id: 1,
          name: '内蒙古风电碳积分项目',
          sku: 'CN-Wind-2023-001',
          images: [
            'https://picsum.photos/seed/wind1/800/600',
            'https://picsum.photos/seed/wind2/800/600',
            'https://picsum.photos/seed/wind3/800/600'
          ],
          rating: 5,
          reviews: 125,
          pricePerCredit: '58.00',
          availableQuantity: 5000,
          carbonReduction: 12500,
          category: 4,
          region: '华北地区',
          tags: ['国际认证', '大型项目'],
          dateAdded: '2023-01-15',
          shortDescription: '该项目位于内蒙古高原，总装机容量500MW，年发电量约15亿千瓦时，可减少二氧化碳排放约125万吨。',
          fullDescription: `
            <h5>项目概况</h5>
            <p>内蒙古风电碳积分项目位于内蒙古自治区锡林郭勒盟，总投资约40亿元人民币，总装机容量500MW。项目于2022年6月建成并网发电，预计运营期25年。</p>

            <h5>环境效益</h5>
            <p>项目全生命周期可减少二氧化碳排放约3125万吨，相当于种植约1.7亿棵树。每年可节约标准煤约50万吨，减少二氧化硫排放约1.5万吨，氮氧化物约8000吨。</p>

            <h5>认证情况</h5>
            <p>本项目已通过国家发改委备案，并获得国际VCS（Verified Carbon Standard）认证，符合联合国清洁发展机制（CDM）标准。</p>

            <h5>社会效益</h5>
            <p>项目建设期间创造就业岗位约1500个，运营期间提供约120个长期工作岗位，有效促进当地经济发展。同时改善了当地能源结构，推动可再生能源发展。</p>
          `,
          specifications: {
            '项目类型': '风力发电',
            '装机容量': '500MW',
            '年发电量': '15亿千瓦时',
            '预计寿命': '25年',
            '认证标准': 'VCS, CDM',
            '开发商': '国家能源集团',
            '开工日期': '2020-09-15',
            '并网日期': '2022-06-30'
          },
          reviewsList: [
            { id: 1, author: '某能源公司', date: '2023-05-15', rating: 5, content: '项目质量高，减排效果显著，已采购10000积分。' },
            { id: 2, author: '碳中和顾问', date: '2023-04-28', rating: 4, content: '流程规范，认证齐全，值得信赖的优质项目。' }
          ]
        },
        // 可以添加更多模拟项目...
      ]

      // 查找匹配的项目
      this.product = mockProjects.find(p => p.id === parseInt(id)) || mockProjects[0]
      this.isLoading = false
    },
    fetchRelatedProjects() {
      // 模拟相关项目数据
      this.relatedProducts = [
        {
          id: 2,
          name: '云南森林碳汇项目',
          image: 'https://picsum.photos/seed/forest1/400/250',
          rating: 4,
          reviews: 98,
          pricePerCredit: '65.00'
        },
        {
          id: 3,
          name: '青海光伏电站项目',
          image: 'https://picsum.photos/seed/solar1/400/250',
          rating: 5,
          reviews: 210,
          pricePerCredit: '52.00'
        },
        {
          id: 4,
          name: '江苏垃圾填埋气回收',
          image: 'https://picsum.photos/seed/biogas1/400/250',
          rating: 4,
          reviews: 76,
          pricePerCredit: '48.00'
        }
      ]
    },
    addToCart() {
      if (this.quantity > this.product.availableQuantity) {
        alert(`超出可购买数量，当前可购买最大数量为${this.product.availableQuantity}`)
        this.quantity = this.product.availableQuantity
        return
      }

      const cartItem = {
        id: this.product.id,
        name: this.product.name,
        image: this.product.images[0],
        price: parseFloat(this.product.pricePerCredit),
        quantity: this.quantity
      }

      // 检查购物车中是否已有该项目
      const existingItemIndex = this.cartItems.findIndex(item => item.id === this.product.id)
      if (existingItemIndex > -1) {
        this.cartItems[existingItemIndex].quantity += this.quantity
      } else {
        this.cartItems.push(cartItem)
      }

      // 保存到本地存储
      localStorage.setItem('cartItems', JSON.stringify(this.cartItems))

      alert(`已添加 ${this.quantity} 积分 ${this.product.name} 到购物车`)

      // 显示购物车侧边栏
      const offcanvas = new window.bootstrap.Offcanvas(document.getElementById('offcanvasCart'))
      offcanvas.show()
    },
    buyNow() {
      this.addToCart()
      // 跳转到结算页面
      // this.$router.push('/checkout')
    },
    removeItem(id) {
      this.cartItems = this.cartItems.filter(item => item.id !== id)
      localStorage.setItem('cartItems', JSON.stringify(this.cartItems))
    },
    checkout() {
      this.$router.push('/checkout')
    },
    setRating(rating) {
      this.newReview.rating = rating
    },
    submitReview() {
      const review = {
        id: Date.now(),
        author: this.newReview.name,
        date: new Date().toISOString().split('T')[0],
        rating: this.newReview.rating,
        content: this.newReview.content
      }

      this.product.reviewsList.unshift(review)
      this.product.reviews++

      this.newReview = {
        rating: 0,
        content: '',
        name: '',
        email: ''
      }

      alert('评价提交成功！感谢您的反馈。')
    }
  },
  mounted() {
    // 从本地存储加载购物车
    const savedCart = localStorage.getItem('cartItems')
    if (savedCart) {
      this.cartItems = JSON.parse(savedCart)
    }
  }
}
</script>

<style scoped>
/* 项目详情页特定样式 */
.single-product-page {
  background-color: #fff;
}

.breadcrumb-item a {
  color: #6c757d;
  text-decoration: none;
}

.banner-section {
  background-image: url('../../public/images/banner-1.jpg');
  background-size: cover;
  background-position: center;
  height: 300px;
  display: flex;
  align-items: center;
  position: relative;
}
.banner-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.2);
}

.banner-content {
  position: relative;
  z-index: 1;
  color: #fff;
  padding: 20px;
}

.banner-title {
  font-size: 48px; /* 增大字体大小，可根据需要调整具体数值 */
  font-weight: bold; /* 可选：增加字重让文字更醒目 */
}

/* 项目图片区域 */
.thumbnail-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  max-height: 600px;
  overflow-y: hidden;
}

.thumbnail-item {
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 5px;
  cursor: pointer;
  transition: all 0.3s;
}

.thumbnail-item:hover, .thumbnail-item.active {
  border-color: #0d6efd;
}

.thumbnail-item img {
  width: 100%;
  height: 100%;
}

.product-main-image {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  background-color: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.product-main-image img {
  max-height: 100%;
  width: 100%;
}

/* 项目信息区域 */
.product-title {
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 10px;
  color: #333;
}

.product-rating {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stars {
  color: #ffb300;
  font-size: 18px;
}

.reviews {
  color: #6c757d;
  font-size: 14px;
}

.product-price {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.current-price {
  font-size: 24px;
  font-weight: 700;
  color: #e53935;
}

.original-price {
  font-size: 18px;
  color: #6c757d;
}

.product-description {
  color: #616161;
  line-height: 1.6;
  margin-bottom: 20px;
}

.project-tags {
  margin-bottom: 20px;
}

/* 数量选择 */
.quantity-selector .input-group {
  width: auto;
}

.quantity-selector input {
  text-align: center;
}

.stock-status {
  font-size: 14px;
  color: #28a745;
  font-weight: 500;
}

/* 操作按钮 */
.product-actions .btn {
  padding: 12px 24px;
  font-weight: 500;
  font-size: 16px;
}

/* 选项卡样式 */
.product-tabs .nav-tabs {
  border-bottom: 1px solid #dee2e6;
}

.product-tabs .nav-link {
  color: #495057;
  border: none;
  padding: 12px 20px;
  font-weight: 500;
}

.product-tabs .nav-link.active {
  color: #0d6efd;
  background-color: #f8f9fa;
  border-bottom: 2px solid #0d6efd;
}

.product-tabs .nav-link:hover:not(.active) {
  color: #0d6efd;
  background-color: #f8f9fa;
}

.product-tabs .tab-content {
  background-color: #f8f9fa;
  min-height: 200px;
}

/* 相关项目 */
.related-products {
  margin-top: 50px;
}

.product-card {
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
  background: #fff;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

.product-card .product-image {
  height: 180px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 15px;
  background-color: #f8f9fa;
}

.product-card .product-image img {
  max-height: 100%;
  max-width: 100%;
}

.product-card .product-info {
  padding: 15px;
}

.product-card .product-name {
  font-size: 16px;
  margin-bottom: 8px;
  height: 40px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

/* 评价样式 */
.review-item {
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.review-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.review-author {
  font-weight: 500;
}

.review-date {
  color: #6c757d;
  font-size: 14px;
}

.review-content {
  color: #495057;
  line-height: 1.6;
}

.rating-stars {
  font-size: 24px;
  color: #ddd;
}

.rating-stars .star {
  cursor: pointer;
  transition: color 0.2s;
}

.rating-stars .star.active {
  color: #ffb300;
}

/* 项目元数据 */
.project-meta {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  font-size: 14px;
}

.project-meta p {
  margin-bottom: 8px;
}
</style>